<?php

namespace app\admin\model\repertory;

use app\common\model\repertory\User as Models;
use think\facade\Cache;

class User extends Models
{
    /**
     * 获取全部
     */
    public static function getAll($store_id)
    {
        $model = new static;
        return $model->where('is_delete', '=', 0)->where('store_id', $store_id)->with(['depts'])->order(['create_time' => 'desc'])->select();
    }

    /**
     * 新增
     */
    public function add($data, $store_id)
    {
        $data["password"] = salt_hash($data["password"]);
        $data["store_id"] = $store_id;
        return $this->save($data);
    }


    /**
     * 软删除
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 更新记录
     */
    public function edit($data)
    {
        if (isset($data["password"])) {
            $data["password"] = salt_hash($data["password"]);
        }
        return $this->save($data);
    }

    /**
     * 超管后台用户登录
     */
    public function login($data)
    {
        // 验证用户名密码是否正确
        if (!$user = self::where([
            'username' => $data['username'],
            'password' => salt_hash($data['password'])
        ])->find()
        ) {
            $this->error = '登录失败, 用户名或密码错误';
            return false;
        }
        // 保存登录状态
        $user['token'] = signToken($user['id'], 'admin');
        Cache::tag('cache')->set('admin_token_' . $user['token'], $user['id'], 86400 * 30);
        return $user;
    }

    /**
     * 超管用户信息
     */
    public static function detail($admin_user_id)
    {
        $model = new static();
        return $model::find($admin_user_id);
    }

    /**
     * 更新当前管理员信息
     */
    public function renew($data)
    {
        if ($data['pass'] !== $data['checkPass']) {
            $this->error = '确认密码不正确';
            return false;
        }
        return $this->save([
            'password' => salt_hash($data['pass']),
        ]);
    }

    /**
     * 获取用户信息
     */
    public static function getUser($data)
    {
        return (new static())->where(['id' => $data['uid']])->find();
    }

}